home *** CD-ROM | disk | FTP | other *** search
/ Nautilus 1992 July / Nautilus-3-8 / Nautilus-3-8.bin / Tools & Utilities / Techy Stuff / Source ƒ / egrep-1.5 / grep-src / dfa.c < prev    next >
Encoding:
Text File  |  1991-10-20  |  58.7 KB  |  2,268 lines

  1. /*  This file has been changed-- it is not the standard FSF version.
  2.  
  3.                          Oct 1991.  */
  4.  
  5.  
  6. /* dfa.c - determinisitic extended regexp routines for GNU
  7.    Copyright (C) 1988 Free Software Foundation, Inc.
  8.                       Written June, 1988 by Mike Haertel
  9.               Modified July, 1988 by Arthur David Olson
  10.              to assist BMG speedups
  11.  
  12.                NO WARRANTY
  13.  
  14.   BECAUSE THIS PROGRAM IS LICENSED FREE OF CHARGE, WE PROVIDE ABSOLUTELY
  15. NO WARRANTY, TO THE EXTENT PERMITTED BY APPLICABLE STATE LAW.  EXCEPT
  16. WHEN OTHERWISE STATED IN WRITING, FREE SOFTWARE FOUNDATION, INC,
  17. RICHARD M. STALLMAN AND/OR OTHER PARTIES PROVIDE THIS PROGRAM "AS IS"
  18. WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
  19. BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  20. FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY
  21. AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE PROGRAM PROVE
  22. DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
  23. CORRECTION.
  24.  
  25.  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL RICHARD M.
  26. STALLMAN, THE FREE SOFTWARE FOUNDATION, INC., AND/OR ANY OTHER PARTY
  27. WHO MAY MODIFY AND REDISTRIBUTE THIS PROGRAM AS PERMITTED BELOW, BE
  28. LIABLE TO YOU FOR DAMAGES, INCLUDING ANY LOST PROFITS, LOST MONIES, OR
  29. OTHER SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  30. USE OR INABILITY TO USE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR
  31. DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY THIRD PARTIES OR
  32. A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS) THIS
  33. PROGRAM, EVEN IF YOU HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
  34. DAMAGES, OR FOR ANY CLAIM BY ANY OTHER PARTY.
  35.  
  36.         GENERAL PUBLIC LICENSE TO COPY
  37.  
  38.   1. You may copy and distribute verbatim copies of this source file
  39. as you receive it, in any medium, provided that you conspicuously and
  40. appropriately publish on each copy a valid copyright notice "Copyright
  41.  (C) 1988 Free Software Foundation, Inc."; and include following the
  42. copyright notice a verbatim copy of the above disclaimer of warranty
  43. and of this License.  You may charge a distribution fee for the
  44. physical act of transferring a copy.
  45.  
  46.   2. You may modify your copy or copies of this source file or
  47. any portion of it, and copy and distribute such modifications under
  48. the terms of Paragraph 1 above, provided that you also do the following:
  49.  
  50.     a) cause the modified files to carry prominent notices stating
  51.     that you changed the files and the date of any change; and
  52.  
  53.     b) cause the whole of any work that you distribute or publish,
  54.     that in whole or in part contains or is a derivative of this
  55.     program or any part thereof, to be licensed at no charge to all
  56.     third parties on terms identical to those contained in this
  57.     License Agreement (except that you may choose to grant more extensive
  58.     warranty protection to some or all third parties, at your option).
  59.  
  60.     c) You may charge a distribution fee for the physical act of
  61.     transferring a copy, and you may at your option offer warranty
  62.     protection in exchange for a fee.
  63.  
  64. Mere aggregation of another unrelated program with this program (or its
  65. derivative) on a volume of a storage or distribution medium does not bring
  66. the other program under the scope of these terms.
  67.  
  68.   3. You may copy and distribute this program or any portion of it in
  69. compiled, executable or object code form under the terms of Paragraphs
  70. 1 and 2 above provided that you do the following:
  71.  
  72.     a) accompany it with the complete corresponding machine-readable
  73.     source code, which must be distributed under the terms of
  74.     Paragraphs 1 and 2 above; or,
  75.  
  76.     b) accompany it with a written offer, valid for at least three
  77.     years, to give any third party free (except for a nominal
  78.     shipping charge) a complete machine-readable copy of the
  79.     corresponding source code, to be distributed under the terms of
  80.     Paragraphs 1 and 2 above; or,
  81.  
  82.     c) accompany it with the information you received as to where the
  83.     corresponding source code may be obtained.  (This alternative is
  84.     allowed only for noncommercial distribution and only if you
  85.     received the program in object code or executable form alone.)
  86.  
  87. For an executable file, complete source code means all the source code for
  88. all modules it contains; but, as a special exception, it need not include
  89. source code for modules which are standard libraries that accompany the
  90. operating system on which the executable file runs.
  91.  
  92.   4. You may not copy, sublicense, distribute or transfer this program
  93. except as expressly provided under this License Agreement.  Any attempt
  94. otherwise to copy, sublicense, distribute or transfer this program is void and
  95. your rights to use the program under this License agreement shall be
  96. automatically terminated.  However, parties who have received computer
  97. software programs from you with this License Agreement will not have
  98. their licenses terminated so long as such parties remain in full compliance.
  99.  
  100.   5. If you wish to incorporate parts of this program into other free
  101. programs whose distribution conditions are different, write to the Free
  102. Software Foundation at 675 Mass Ave, Cambridge, MA 02139.  We have not yet
  103. worked out a simple rule that can be stated here, but we will often permit
  104. this.  We will be guided by the two goals of preserving the free status of
  105. all derivatives our free software and of promoting the sharing and reuse of
  106. software.
  107.  
  108.  
  109. In other words, you are welcome to use, share and improve this program.
  110. You are forbidden to forbid anyone else to use, share and improve
  111. what you give them.   Help stamp out software-hoarding!  */
  112.  
  113. #include <stdio.h>
  114. #include <assert.h>
  115. #include <ctype.h>
  116. #include "dfa.h"
  117.  
  118. #ifdef __STDC__
  119. typedef void *ptr_t;
  120. #else
  121. typedef char *ptr_t;
  122. #endif
  123.  
  124. static void    regmust();
  125.  
  126. static ptr_t
  127. xcalloc(n, s)
  128.      int n;
  129.      size_t s;
  130. {
  131.   ptr_t r = calloc(n, s);
  132.  
  133.   if (r)
  134.     return r;
  135.   else
  136.     regerror("Memory exhausted");
  137. }
  138.  
  139. ptr_t
  140. xmalloc(n)
  141.      size_t n;
  142. {
  143.   ptr_t r = malloc(n);
  144.  
  145.   assert(n != 0);
  146.   if (r)
  147.     return r;
  148.   else
  149.     regerror("Memory exhausted");
  150. }
  151.  
  152. static ptr_t
  153. xrealloc(p, n)
  154.      ptr_t p;
  155.      size_t n;
  156. {
  157.   ptr_t r = realloc(p, n);
  158.  
  159.   assert(n != 0);
  160.   if (r)
  161.     return r;
  162.   else
  163.     regerror("Memory exhausted");
  164. }
  165.  
  166. #define CALLOC(p, t, n) ((p) = (t *) xcalloc((n), sizeof (t)))
  167. #define MALLOC(p, t, n) ((p) = (t *) xmalloc((n) * sizeof (t)))
  168. #define REALLOC(p, t, n) ((p) = (t *) xrealloc((ptr_t) (p), (n) * sizeof (t)))
  169.  
  170. /* Reallocate an array of type t if nalloc is too small for index. */
  171. #define REALLOC_IF_NECESSARY(p, t, nalloc, index) \
  172.   if ((index) >= (nalloc))              \
  173.     {                          \
  174.       while ((index) >= (nalloc))          \
  175.     (nalloc) *= 2;                  \
  176.       REALLOC(p, t, nalloc);              \
  177.     }
  178.  
  179. /* Stuff pertaining to charsets. */
  180.  
  181. static
  182. tstbit(b, c)
  183.      int b;
  184.      _charset c;
  185. {
  186.   return c[b / INTBITS] & 1 << b % INTBITS;
  187. }
  188.  
  189. static void
  190. setbit(b, c)
  191.      int b;
  192.      _charset c;
  193. {
  194.   c[b / INTBITS] |= 1 << b % INTBITS;
  195. }
  196.  
  197. static void
  198. clrbit(b, c)
  199.      int b;
  200.      _charset c;
  201. {
  202.   c[b / INTBITS] &= ~(1 << b % INTBITS);
  203. }
  204.  
  205. static void
  206. copyset(src, dst)
  207.      const _charset src;
  208.      _charset dst;
  209. {
  210.   int i;
  211.  
  212.   for (i = 0; i < _CHARSET_INTS; ++i)
  213.     dst[i] = src[i];
  214. }
  215.  
  216. static void
  217. zeroset(s)
  218.      _charset s;
  219. {
  220.   int i;
  221.  
  222.   for (i = 0; i < _CHARSET_INTS; ++i)
  223.     s[i] = 0;
  224. }
  225.  
  226. static void
  227. notset(s)
  228.      _charset s;
  229. {
  230.   int i;
  231.  
  232.   for (i = 0; i < _CHARSET_INTS; ++i)
  233.     s[i] = ~s[i];
  234. }
  235.  
  236. static
  237. equal(s1, s2)
  238.      const _charset s1;
  239.      const _charset s2;
  240. {
  241.   int i;
  242.  
  243.   for (i = 0; i < _CHARSET_INTS; ++i)
  244.     if (s1[i] != s2[i])
  245.       return 0;
  246.   return 1;
  247. }
  248.  
  249. /* A pointer to the current regexp is kept here during parsing. */
  250. static struct regexp *reg;
  251.  
  252. /* Find the index of charset s in reg->charsets, or allocate a new charset. */
  253. static
  254. charset_index(s)
  255.      const _charset s;
  256. {
  257.   int i;
  258.  
  259.   for (i = 0; i < reg->cindex; ++i)
  260.     if (equal(s, reg->charsets[i]))
  261.       return i;
  262.   REALLOC_IF_NECESSARY(reg->charsets, _charset, reg->calloc, reg->cindex);
  263.   ++reg->cindex;
  264.   copyset(s, reg->charsets[i]);
  265.   return i;
  266. }
  267.  
  268. /* Syntax bits controlling the behavior of the lexical analyzer. */
  269. static syntax_bits, syntax_bits_set;
  270.  
  271. /* Flag for case-folding letters into sets. */
  272. static case_fold;
  273.  
  274. /* Entry point to set syntax options. */
  275. void
  276. regsyntax(bits, fold)
  277.      int bits;
  278.      int fold;
  279. {
  280.   syntax_bits_set = 1;
  281.   syntax_bits = bits;
  282.   case_fold = fold;
  283. }
  284.  
  285. /* Lexical analyzer. */
  286. static const char *lexstart;    /* Pointer to beginning of input string. */
  287. static const char *lexptr;    /* Pointer to next input character. */
  288. static lexleft;            /* Number of characters remaining. */
  289. static caret_allowed;        /* True if backward context allows ^
  290.                    (meaningful only if RE_CONTEXT_INDEP_OPS
  291.                    is turned off). */
  292. static closure_allowed;        /* True if backward context allows closures
  293.                    (meaningful only if RE_CONTEXT_INDEP_OPS
  294.                    is turned off). */
  295.  
  296. /* Note that characters become unsigned here. */
  297. #ifdef sparc
  298. /*
  299.  * Sun4 4.0.1 C compiler can't compare constant strings correctly.
  300.  * e.g. if("test") { x; } else { y; }
  301.  * the compiler will not generate code to execute { x; }, but
  302.  * executes { y; } instead.
  303.  */
  304. #define FETCH0(c)                 \
  305.   {                         \
  306.     if (! lexleft)                 \
  307.       return _END;                 \
  308.     (c) = (unsigned char) *lexptr++;  \
  309.     --lexleft;                     \
  310.   }
  311. #define FETCH(c, eoferr)             \
  312.   {                         \
  313.     if (! lexleft)                 \
  314.       regerror(eoferr);            \
  315.     (c) = (unsigned char) *lexptr++;  \
  316.     --lexleft;                     \
  317.   }
  318. #else
  319. #define FETCH(c, eoferr)             \
  320.   {                         \
  321.     if (! lexleft)                 \
  322.       if (eoferr)                 \
  323.     regerror(eoferr);            \
  324.       else                     \
  325.     return _END;                 \
  326.     (c) = (unsigned char) *lexptr++;  \
  327.     --lexleft;                     \
  328.   }
  329. #endif
  330.  
  331. static _token
  332. lex()
  333. {
  334.   _token c, c2;
  335.   int invert;
  336.   _charset cset;
  337.  
  338. #ifdef sparc
  339.   FETCH0(c);
  340. #else
  341.   FETCH(c, (char *) 0);
  342. #endif
  343.   switch (c)
  344.     {
  345.     case '^':
  346.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS)
  347.       && (!caret_allowed ||
  348.           (syntax_bits & RE_TIGHT_VBAR) && lexptr - 1 != lexstart))
  349.     goto normal_char;
  350.       caret_allowed = 0;
  351.       return syntax_bits & RE_TIGHT_VBAR ? _ALLBEGLINE : _BEGLINE;
  352.  
  353.     case '$':
  354.       if (syntax_bits & RE_CONTEXT_INDEP_OPS || !lexleft
  355.       || (! (syntax_bits & RE_TIGHT_VBAR)
  356.           && ((syntax_bits & RE_NO_BK_PARENS
  357.            ? lexleft > 0 && *lexptr == ')'
  358.            : lexleft > 1 && *lexptr == '\\' && lexptr[1] == ')')
  359.           || (syntax_bits & RE_NO_BK_VBAR
  360.               ? lexleft > 0 && *lexptr == '|'
  361.               : lexleft > 1 && *lexptr == '\\' && lexptr[1] == '|'))))
  362.     return syntax_bits & RE_TIGHT_VBAR ? _ALLENDLINE : _ENDLINE;
  363.       goto normal_char;
  364.  
  365.     case '\\':
  366.       FETCH(c, "Unfinished \\ quote");
  367.       switch (c)
  368.     {
  369.     case '1':
  370.     case '2':
  371.     case '3':
  372.     case '4':
  373.     case '5':
  374.     case '6':
  375.     case '7':
  376.     case '8':
  377.     case '9':
  378.       caret_allowed = 0;
  379.       closure_allowed = 1;
  380.       return _BACKREF;
  381.  
  382.     case '<':
  383.       caret_allowed = 0;
  384.       return _BEGWORD;
  385.  
  386.     case '>':
  387.       caret_allowed = 0;
  388.       return _ENDWORD;
  389.  
  390.     case 'b':
  391.       caret_allowed = 0;
  392.       return _LIMWORD;
  393.  
  394.     case 'B':
  395.       caret_allowed = 0;
  396.       return _NOTLIMWORD;
  397.  
  398.     case 'w':
  399.     case 'W':
  400.       zeroset(cset);
  401.       for (c2 = 0; c2 < _NOTCHAR; ++c2)
  402.         if (ISALNUM(c2))
  403.           setbit(c2, cset);
  404.       if (c == 'W')
  405.         notset(cset);
  406.       caret_allowed = 0;
  407.       closure_allowed = 1;
  408.       return _SET + charset_index(cset);
  409.  
  410.     case '?':
  411.       if (syntax_bits & RE_BK_PLUS_QM)
  412.         goto qmark;
  413.       goto normal_char;
  414.  
  415.     case '+':
  416.       if (syntax_bits & RE_BK_PLUS_QM)
  417.         goto plus;
  418.       goto normal_char;
  419.  
  420.     case '|':
  421.       if (! (syntax_bits & RE_NO_BK_VBAR))
  422.         goto or;
  423.       goto normal_char;
  424.  
  425.     case '(':
  426.       if (! (syntax_bits & RE_NO_BK_PARENS))
  427.         goto lparen;
  428.       goto normal_char;
  429.  
  430.     case ')':
  431.       if (! (syntax_bits & RE_NO_BK_PARENS))
  432.         goto rparen;
  433.       goto normal_char;
  434.  
  435.     default:
  436.       goto normal_char;
  437.     }
  438.  
  439.     case '?':
  440.       if (syntax_bits & RE_BK_PLUS_QM)
  441.     goto normal_char;
  442.     qmark:
  443.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  444.     goto normal_char;
  445.       return _QMARK;
  446.  
  447.     case '*':
  448.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  449.     goto normal_char;
  450.       return _STAR;
  451.  
  452.     case '+':
  453.       if (syntax_bits & RE_BK_PLUS_QM)
  454.     goto normal_char;
  455.     plus:
  456.       if (! (syntax_bits & RE_CONTEXT_INDEP_OPS) && !closure_allowed)
  457.     goto normal_char;
  458.       return _PLUS;
  459.  
  460.     case '|':
  461.       if (! (syntax_bits & RE_NO_BK_VBAR))
  462.     goto normal_char;
  463.     or:
  464.       caret_allowed = 1;
  465.       closure_allowed = 0;
  466.       return _OR;
  467.  
  468.     case '\r':   /* newline changed */
  469.       if (! (syntax_bits & RE_NEWLINE_OR))
  470.     goto normal_char;
  471.       goto or;
  472.  
  473.     case '(':
  474.       if (! (syntax_bits & RE_NO_BK_PARENS))
  475.     goto normal_char;
  476.     lparen:
  477.       caret_allowed = 1;
  478.       closure_allowed = 0;
  479.       return _LPAREN;
  480.  
  481.     case ')':
  482.       if (! (syntax_bits & RE_NO_BK_PARENS))
  483.     goto normal_char;
  484.     rparen:
  485.       caret_allowed = 0;
  486.       closure_allowed = 1;
  487.       return _RPAREN;
  488.  
  489.     case '.':
  490.       zeroset(cset);
  491.       notset(cset);
  492.       clrbit('\r', cset); /* newline changed */
  493.       caret_allowed = 0;
  494.       closure_allowed = 1;
  495.       return _SET + charset_index(cset);
  496.  
  497.     case '[':
  498.       zeroset(cset);
  499.       FETCH(c, "Unbalanced [");
  500.       if (c == '^')
  501.     {
  502.       FETCH(c, "Unbalanced [");
  503.       invert = 1;
  504.     }
  505.       else
  506.     invert = 0;
  507.       do
  508.     {
  509.       FETCH(c2, "Unbalanced [");
  510.       if (c2 == '-')
  511.         {
  512.           FETCH(c2, "Unbalanced [");
  513.           while (c <= c2)
  514.           setbit(c++, cset);
  515.           FETCH(c, "Unbalanced [");
  516.         }
  517.       else
  518.         {
  519.           setbit(c, cset);
  520.           c = c2;
  521.         }
  522.     }
  523.       while (c != ']');
  524.       if (invert)
  525.     notset(cset);
  526.       caret_allowed = 0;
  527.       closure_allowed = 1;
  528.       return _SET + charset_index(cset);
  529.  
  530.     default:
  531.     normal_char:
  532.       caret_allowed = 0;
  533.       closure_allowed = 1;
  534.       if (case_fold && ISALPHA(c))
  535.     {
  536.       zeroset(cset);
  537.       if (isupper(c))
  538.         c = tolower(c);
  539.       setbit(c, cset);
  540.       setbit(toupper(c), cset);
  541.       return _SET + charset_index(cset);
  542.     }
  543.       return c;
  544.     }
  545. }
  546.  
  547. /* Recursive descent parser for regular expressions. */
  548.  
  549. static _token tok;        /* Lookahead token. */
  550. static depth;            /* Current depth of a hypothetical stack
  551.                    holding deferred productions.  This is
  552.                    used to determine the depth that will be
  553.                    required of the real stack later on in
  554.                    reganalyze(). */
  555.  
  556. /* Add the given token to the parse tree, maintaining the depth count and
  557.    updating the maximum depth if necessary. */
  558. static void
  559. addtok(t)
  560.      _token t;
  561. {
  562.   REALLOC_IF_NECESSARY(reg->tokens, _token, reg->talloc, reg->tindex);
  563.   reg->tokens[reg->tindex++] = t;
  564.  
  565.   switch (t)
  566.     {
  567.     case _QMARK:
  568.     case _STAR:
  569.     case _PLUS:
  570.       break;
  571.  
  572.     case _CAT:
  573.     case _OR:
  574.       --depth;
  575.       break;
  576.  
  577.     default:
  578.       ++reg->nleaves;
  579.     case _EMPTY:
  580.       ++depth;
  581.       break;
  582.     }
  583.   if (depth > reg->depth)
  584.     reg->depth = depth;
  585. }
  586.  
  587. /* The grammar understood by the parser is as follows.
  588.  
  589.    start:
  590.      regexp
  591.      _ALLBEGLINE regexp
  592.      regexp _ALLENDLINE
  593.      _ALLBEGLINE regexp _ALLENDLINE
  594.  
  595.    regexp:
  596.      regexp _OR branch
  597.      branch
  598.  
  599.    branch:
  600.      branch closure
  601.      closure
  602.  
  603.    closure:
  604.      closure _QMARK
  605.      closure _STAR
  606.      closure _PLUS
  607.      atom
  608.  
  609.    atom:
  610.      <normal character>
  611.      _SET
  612.      _BACKREF
  613.      _BEGLINE
  614.      _ENDLINE
  615.      _BEGWORD
  616.      _ENDWORD
  617.      _LIMWORD
  618.      _NOTLIMWORD
  619.      <empty>
  620.  
  621.    The parser builds a parse tree in postfix form in an array of tokens. */
  622.  
  623. #ifdef __STDC__
  624. static void regexp();
  625. #else
  626. static void regexp();
  627. #endif
  628.  
  629. static void
  630. atom()
  631. {
  632.   if (tok >= 0 && tok < _NOTCHAR || tok >= _SET || tok == _BACKREF
  633.       || tok == _BEGLINE || tok == _ENDLINE || tok == _BEGWORD
  634.       || tok == _ENDWORD || tok == _LIMWORD || tok == _NOTLIMWORD)
  635.     {
  636.       addtok(tok);
  637.       tok = lex();
  638.     }
  639.   else if (tok == _LPAREN)
  640.     {
  641.       tok = lex();
  642.       regexp();
  643.       if (tok != _RPAREN)
  644.     regerror("Unbalanced (");
  645.       tok = lex();
  646.     }
  647.   else
  648.     addtok(_EMPTY);
  649. }
  650.  
  651. static void
  652. closure()
  653. {
  654.   atom();
  655.   while (tok == _QMARK || tok == _STAR || tok == _PLUS)
  656.     {
  657.       addtok(tok);
  658.       tok = lex();
  659.     }
  660. }
  661.  
  662. static void
  663. branch()
  664. {
  665.   closure();
  666.   while (tok != _RPAREN && tok != _OR && tok != _ALLENDLINE && tok >= 0)
  667.     {
  668.       closure();
  669.       addtok(_CAT);
  670.     }
  671. }
  672.  
  673. static void
  674. regexp()
  675. {
  676.   branch();
  677.   while (tok == _OR)
  678.     {
  679.       tok = lex();
  680.       branch();
  681.       addtok(_OR);
  682.     }
  683. }
  684.  
  685. /* Main entry point for the parser.  S is a string to be parsed, len is the
  686.    length of the string, so s can include NUL characters.  R is a pointer to
  687.    the struct regexp to parse into. */
  688. void
  689. regparse(s, len, r)
  690.      const char *s;
  691.      size_t len;
  692.      struct regexp *r;
  693. {
  694.   reg = r;
  695.   lexstart = lexptr = s;
  696.   lexleft = len;
  697.   caret_allowed = 1;
  698.   closure_allowed = 0;
  699.  
  700.   if (! syntax_bits_set)
  701.     regerror("No syntax specified");
  702.  
  703.   tok = lex();
  704.   depth = r->depth;
  705.  
  706.   if (tok == _ALLBEGLINE)
  707.     {
  708.       addtok(_BEGLINE);
  709.       tok = lex();
  710.       regexp();
  711.       addtok(_CAT);
  712.     }
  713.   else
  714.     regexp();
  715.  
  716.   if (tok == _ALLENDLINE)
  717.     {
  718.       addtok(_ENDLINE);
  719.       addtok(_CAT);
  720.       tok = lex();
  721.     }
  722.  
  723.   if (tok != _END)
  724.     regerror("Unbalanced )");
  725.  
  726.   addtok(_END - r->nregexps);
  727.   addtok(_CAT);
  728.  
  729.   if (r->nregexps)
  730.     addtok(_OR);
  731.  
  732.   ++r->nregexps;
  733. }
  734.  
  735. /* Some primitives for operating on sets of positions. */
  736.  
  737. /* Copy one set to another; the destination must be large enough. */
  738. static void
  739. copy(src, dst)
  740.      const _position_set *src;
  741.      _position_set *dst;
  742. {
  743.   int i;
  744.  
  745.   for (i = 0; i < src->nelem; ++i)
  746.     dst->elems[i] = src->elems[i];
  747.   dst->nelem = src->nelem;
  748. }
  749.  
  750. /* Insert a position in a set.  Position sets are maintained in sorted
  751.    order according to index.  If position already exists in the set with
  752.    the same index then their constraints are logically or'd together.
  753.    S->elems must point to an array large enough to hold the resulting set. */
  754. static void
  755. insert(p, s)
  756.      _position p;
  757.      _position_set *s;
  758. {
  759.   int i;
  760.   _position t1, t2;
  761.  
  762.   for (i = 0; i < s->nelem && p.index < s->elems[i].index; ++i)
  763.     ;
  764.   if (i < s->nelem && p.index == s->elems[i].index)
  765.     s->elems[i].constraint |= p.constraint;
  766.   else
  767.     {
  768.       t1 = p;
  769.       ++s->nelem;
  770.       while (i < s->nelem)
  771.     {
  772.       t2 = s->elems[i];
  773.       s->elems[i++] = t1;
  774.       t1 = t2;
  775.     }
  776.     }
  777. }
  778.  
  779. /* Merge two sets of positions into a third.  The result is exactly as if
  780.    the positions of both sets were inserted into an initially empty set. */
  781. static void
  782. merge(s1, s2, m)
  783.      _position_set *s1;
  784.      _position_set *s2;
  785.      _position_set *m;
  786. {
  787.   int i = 0, j = 0;
  788.  
  789.   m->nelem = 0;
  790.   while (i < s1->nelem && j < s2->nelem)
  791.     if (s1->elems[i].index > s2->elems[j].index)
  792.       m->elems[m->nelem++] = s1->elems[i++];
  793.     else if (s1->elems[i].index < s2->elems[j].index)
  794.       m->elems[m->nelem++] = s2->elems[j++];
  795.     else
  796.       {
  797.     m->elems[m->nelem] = s1->elems[i++];
  798.     m->elems[m->nelem++].constraint |= s2->elems[j++].constraint;
  799.       }
  800.   while (i < s1->nelem)
  801.     m->elems[m->nelem++] = s1->elems[i++];
  802.   while (j < s2->nelem)
  803.     m->elems[m->nelem++] = s2->elems[j++];
  804. }
  805.  
  806. /* Delete a position from a set. */
  807. static void
  808. delete(p, s)
  809.      _position p;
  810.      _position_set *s;
  811. {
  812.   int i;
  813.  
  814.   for (i = 0; i < s->nelem; ++i)
  815.     if (p.index == s->elems[i].index)
  816.       break;
  817.   if (i < s->nelem)
  818.     for (--s->nelem; i < s->nelem; ++i)
  819.       s->elems[i] = s->elems[i + 1];
  820. }
  821.  
  822. /* Find the index of the state corresponding to the given position set with
  823.    the given preceding context, or create a new state if there is no such
  824.    state.  Newline and letter tell whether we got here on a newline or
  825.    letter, respectively. */
  826. static
  827. state_index(r, s, newline, letter)
  828.      struct regexp *r;
  829.      _position_set *s;
  830.      int newline;
  831.      int letter;
  832. {
  833.   int hash = 0;
  834.   int constraint;
  835.   int i, j;
  836.  
  837.   newline = newline ? 1 : 0;
  838.   letter = letter ? 1 : 0;
  839.  
  840.   for (i = 0; i < s->nelem; ++i)
  841.     hash ^= s->elems[i].index + s->elems[i].constraint;
  842.  
  843.   /* Try to find a state that exactly matches the proposed one. */
  844.   for (i = 0; i < r->sindex; ++i)
  845.     {
  846.       if (hash != r->states[i].hash || s->nelem != r->states[i].elems.nelem
  847.       || newline != r->states[i].newline || letter != r->states[i].letter)
  848.     continue;
  849.       for (j = 0; j < s->nelem; ++j)
  850.     if (s->elems[j].constraint
  851.         != r->states[i].elems.elems[j].constraint
  852.         || s->elems[j].index != r->states[i].elems.elems[j].index)
  853.       break;
  854.       if (j == s->nelem)
  855.     return i;
  856.     }
  857.  
  858.   /* We'll have to create a new state. */
  859.   REALLOC_IF_NECESSARY(r->states, _dfa_state, r->salloc, r->sindex);
  860.   r->states[i].hash = hash;
  861.   MALLOC(r->states[i].elems.elems, _position, s->nelem);
  862.   copy(s, &r->states[i].elems);
  863.   r->states[i].newline = newline;
  864.   r->states[i].letter = letter;
  865.   r->states[i].backref = 0;
  866.   r->states[i].constraint = 0;
  867.   r->states[i].first_end = 0;
  868.   for (j = 0; j < s->nelem; ++j)
  869.     if (r->tokens[s->elems[j].index] < 0)
  870.       {
  871.     constraint = s->elems[j].constraint;
  872.     if (_SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 0)
  873.         || _SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 1)
  874.         || _SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 0)
  875.         || _SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 1))
  876.       r->states[i].constraint |= constraint;
  877.     if (! r->states[i].first_end)
  878.       r->states[i].first_end = r->tokens[s->elems[j].index];
  879.       }
  880.     else if (r->tokens[s->elems[j].index] == _BACKREF)
  881.       {
  882.     r->states[i].constraint = _NO_CONSTRAINT;
  883.     r->states[i].backref = 1;
  884.       }
  885.  
  886.   ++r->sindex;
  887.  
  888.   return i;
  889. }
  890.  
  891. /* Find the epsilon closure of a set of positions.  If any position of the set
  892.    contains a symbol that matches the empty string in some context, replace
  893.    that position with the elements of its follow labeled with an appropriate
  894.    constraint.  Repeat exhaustively until no funny positions are left.
  895.    S->elems must be large enough to hold the result. */
  896. epsclosure(s, r)
  897.      _position_set *s;
  898.      struct regexp *r;
  899. {
  900.   int i, j;
  901.   int *visited;
  902.   _position p, old;
  903.  
  904.   MALLOC(visited, int, r->tindex);
  905.   for (i = 0; i < r->tindex; ++i)
  906.     visited[i] = 0;
  907.  
  908.   for (i = 0; i < s->nelem; ++i)
  909.     if (r->tokens[s->elems[i].index] >= _NOTCHAR
  910.     && r->tokens[s->elems[i].index] != _BACKREF
  911.     && r->tokens[s->elems[i].index] < _SET)
  912.       {
  913.     old = s->elems[i];
  914.     p.constraint = old.constraint;
  915.     delete(s->elems[i], s);
  916.     if (visited[old.index])
  917.       {
  918.         --i;
  919.         continue;
  920.       }
  921.     visited[old.index] = 1;
  922.     switch (r->tokens[old.index])
  923.       {
  924.       case _BEGLINE:
  925.         p.constraint &= _BEGLINE_CONSTRAINT;
  926.         break;
  927.       case _ENDLINE:
  928.         p.constraint &= _ENDLINE_CONSTRAINT;
  929.         break;
  930.       case _BEGWORD:
  931.         p.constraint &= _BEGWORD_CONSTRAINT;
  932.         break;
  933.       case _ENDWORD:
  934.         p.constraint &= _ENDWORD_CONSTRAINT;
  935.         break;
  936.       case _LIMWORD:
  937.         p.constraint &= _ENDWORD_CONSTRAINT;
  938.         break;
  939.       case _NOTLIMWORD:
  940.         p.constraint &= _NOTLIMWORD_CONSTRAINT;
  941.         break;
  942.       }
  943.     for (j = 0; j < r->follows[old.index].nelem; ++j)
  944.       {
  945.         p.index = r->follows[old.index].elems[j].index;
  946.         insert(p, s);
  947.       }
  948.     /* Force rescan to start at the beginning. */
  949.     i = -1;
  950.       }
  951.  
  952.   free(visited);
  953. }
  954.  
  955. /* Perform bottom-up analysis on the parse tree, computing various functions.
  956.    Note that at this point, we're pretending constructs like \< are real
  957.    characters rather than constraints on what can follow them.
  958.  
  959.    Nullable:  A node is nullable if it is at the root of a regexp that can
  960.    match the empty string.
  961.    *  _EMPTY leaves are nullable.
  962.    * No other leaf is nullable.
  963.    * A _QMARK or _STAR node is nullable.
  964.    * A _PLUS node is nullable if its argument is nullable.
  965.    * A _CAT node is nullable if both its arguments are nullable.
  966.    * An _OR node is nullable if either argument is nullable.
  967.  
  968.    Firstpos:  The firstpos of a node is the set of positions (nonempty leaves)
  969.    that could correspond to the first character of a string matching the
  970.    regexp rooted at the given node.
  971.    * _EMPTY leaves have empty firstpos.
  972.    * The firstpos of a nonempty leaf is that leaf itself.
  973.    * The firstpos of a _QMARK, _STAR, or _PLUS node is the firstpos of its
  974.      argument.
  975.    * The firstpos of a _CAT node is the firstpos of the left argument, union
  976.      the firstpos of the right if the left argument is nullable.
  977.    * The firstpos of an _OR node is the union of firstpos of each argument.
  978.  
  979.    Lastpos:  The lastpos of a node is the set of positions that could
  980.    correspond to the last character of a string matching the regexp at
  981.    the given node.
  982.    * _EMPTY leaves have empty lastpos.
  983.    * The lastpos of a nonempty leaf is that leaf itself.
  984.    * The lastpos of a _QMARK, _STAR, or _PLUS node is the lastpos of its
  985.      argument.
  986.    * The lastpos of a _CAT node is the lastpos of its right argument, union
  987.      the lastpos of the left if the right argument is nullable.
  988.    * The lastpos of an _OR node is the union of the lastpos of each argument.
  989.  
  990.    Follow:  The follow of a position is the set of positions that could
  991.    correspond to the character following a character matching the node in
  992.    a string matching the regexp.  At this point we consider special symbols
  993.    that match the empty string in some context to be just normal characters.
  994.    Later, if we find that a special symbol is in a follow set, we will
  995.    replace it with the elements of its follow, labeled with an appropriate
  996.    constraint.
  997.    * Every node in the firstpos of the argument of a _STAR or _PLUS node is in
  998.      the follow of every node in the lastpos.
  999.    * Every node in the firstpos of the second argument of a _CAT node is in
  1000.      the follow of every node in the lastpos of the first argument.
  1001.  
  1002.    Because of the postfix representation of the parse tree, the depth-first
  1003.    analysis is conveniently done by a linear scan with the aid of a stack.
  1004.    Sets are stored as arrays of the elements, obeying a stack-like allocation
  1005.    scheme; the number of elements in each set deeper in the stack can be
  1006.    used to determine the address of a particular set's array. */
  1007. void
  1008. reganalyze(r, searchflag)
  1009.      struct regexp *r;
  1010.      int searchflag;
  1011. {
  1012.   int *nullable;        /* Nullable stack. */
  1013.   int *nfirstpos;        /* Element count stack for firstpos sets. */
  1014.   _position *firstpos;        /* Array where firstpos elements are stored. */
  1015.   int *nlastpos;        /* Element count stack for lastpos sets. */
  1016.   _position *lastpos;        /* Array where lastpos elements are stored. */
  1017.   int *nalloc;            /* Sizes of arrays allocated to follow sets. */
  1018.   _position_set tmp;        /* Temporary set for merging sets. */
  1019.   _position_set merged;        /* Result of merging sets. */
  1020.   int wants_newline;        /* True if some position wants newline info. */
  1021.   int *o_nullable;
  1022.   int *o_nfirst, *o_nlast;
  1023.   _position *o_firstpos, *o_lastpos;
  1024.   int i, j;
  1025.   _position *pos;
  1026.  
  1027.   r->searchflag = searchflag;
  1028.  
  1029.   MALLOC(nullable, int, r->depth);
  1030.   o_nullable = nullable;
  1031.   MALLOC(nfirstpos, int, r->depth);
  1032.   o_nfirst = nfirstpos;
  1033.   MALLOC(firstpos, _position, r->nleaves);
  1034.   o_firstpos = firstpos, firstpos += r->nleaves;
  1035.   MALLOC(nlastpos, int, r->depth);
  1036.   o_nlast = nlastpos;
  1037.   MALLOC(lastpos, _position, r->nleaves);
  1038.   o_lastpos = lastpos, lastpos += r->nleaves;
  1039.   MALLOC(nalloc, int, r->tindex);
  1040.   for (i = 0; i < r->tindex; ++i)
  1041.     nalloc[i] = 0;
  1042.   MALLOC(merged.elems, _position, r->nleaves);
  1043.  
  1044.   CALLOC(r->follows, _position_set, r->tindex);
  1045.  
  1046.   for (i = 0; i < r->tindex; ++i)
  1047.     switch (r->tokens[i])
  1048.       {
  1049.       case _EMPTY:
  1050.     /* The empty set is nullable. */
  1051.     *nullable++ = 1;
  1052.  
  1053.     /* The firstpos and lastpos of the empty leaf are both empty. */
  1054.     *nfirstpos++ = *nlastpos++ = 0;
  1055.     break;
  1056.  
  1057.       case _STAR:
  1058.       case _PLUS:
  1059.     /* Every element in the firstpos of the argument is in the follow
  1060.        of every element in the lastpos. */
  1061.     tmp.nelem = nfirstpos[-1];
  1062.     tmp.elems = firstpos;
  1063.     pos = lastpos;
  1064.     for (j = 0; j < nlastpos[-1]; ++j)
  1065.       {
  1066.         merge(&tmp, &r->follows[pos[j].index], &merged);
  1067.         REALLOC_IF_NECESSARY(r->follows[pos[j].index].elems, _position,
  1068.                  nalloc[pos[j].index], merged.nelem - 1);
  1069.         copy(&merged, &r->follows[pos[j].index]);
  1070.       }
  1071.  
  1072.       case _QMARK:
  1073.     /* A _QMARK or _STAR node is automatically nullable. */
  1074.     if (r->tokens[i] != _PLUS)
  1075.       nullable[-1] = 1;
  1076.     break;
  1077.  
  1078.       case _CAT:
  1079.     /* Every element in the firstpos of the second argument is in the
  1080.        follow of every element in the lastpos of the first argument. */
  1081.     tmp.nelem = nfirstpos[-1];
  1082.     tmp.elems = firstpos;
  1083.     pos = lastpos + nlastpos[-1];
  1084.     for (j = 0; j < nlastpos[-2]; ++j)
  1085.       {
  1086.         merge(&tmp, &r->follows[pos[j].index], &merged);
  1087.         REALLOC_IF_NECESSARY(r->follows[pos[j].index].elems, _position,
  1088.                  nalloc[pos[j].index], merged.nelem - 1);
  1089.         copy(&merged, &r->follows[pos[j].index]);
  1090.       }
  1091.  
  1092.     /* The firstpos of a _CAT node is the firstpos of the first argument,
  1093.        union that of the second argument if the first is nullable. */
  1094.     if (nullable[-2])
  1095.       nfirstpos[-2] += nfirstpos[-1];
  1096.     else
  1097.       firstpos += nfirstpos[-1];
  1098.     --nfirstpos;
  1099.  
  1100.     /* The lastpos of a _CAT node is the lastpos of the second argument,
  1101.        union that of the first argument if the second is nullable. */
  1102.     if (nullable[-1])
  1103.       nlastpos[-2] += nlastpos[-1];
  1104.     else
  1105.       {
  1106.         pos = lastpos + nlastpos[-2];
  1107.         for (j = nlastpos[-1] - 1; j >= 0; --j)
  1108.           pos[j] = lastpos[j];
  1109.         lastpos += nlastpos[-2];
  1110.         nlastpos[-2] = nlastpos[-1];
  1111.       }
  1112.     --nlastpos;
  1113.  
  1114.     /* A _CAT node is nullable if both arguments are nullable. */
  1115.     nullable[-2] = nullable[-1] && nullable[-2];
  1116.     --nullable;
  1117.     break;
  1118.  
  1119.       case _OR:
  1120.     /* The firstpos is the union of the firstpos of each argument. */
  1121.     nfirstpos[-2] += nfirstpos[-1];
  1122.     --nfirstpos;
  1123.  
  1124.     /* The lastpos is the union of the lastpos of each argument. */
  1125.     nlastpos[-2] += nlastpos[-1];
  1126.     --nlastpos;
  1127.  
  1128.     /* An _OR node is nullable if either argument is nullable. */
  1129.     nullable[-2] = nullable[-1] || nullable[-2];
  1130.     --nullable;
  1131.     break;
  1132.  
  1133.       default:
  1134.     /* Anything else is a nonempty position.  (Note that special
  1135.        constructs like \< are treated as nonempty strings here;
  1136.        an "epsilon closure" effectively makes them nullable later.
  1137.        Backreferences have to get a real position so we can detect
  1138.        transitions on them later.  But they are nullable. */
  1139.     *nullable++ = r->tokens[i] == _BACKREF;
  1140.  
  1141.     /* This position is in its own firstpos and lastpos. */
  1142.     *nfirstpos++ = *nlastpos++ = 1;
  1143.     --firstpos, --lastpos;
  1144.     firstpos->index = lastpos->index = i;
  1145.     firstpos->constraint = lastpos->constraint = _NO_CONSTRAINT;
  1146.  
  1147.     /* Allocate the follow set for this position. */
  1148.     nalloc[i] = 1;
  1149.     MALLOC(r->follows[i].elems, _position, nalloc[i]);
  1150.     break;
  1151.       }
  1152.  
  1153.   /* For each follow set that is the follow set of a real position, replace
  1154.      it with its epsilon closure. */
  1155.   for (i = 0; i < r->tindex; ++i)
  1156.     if (r->tokens[i] < _NOTCHAR || r->tokens[i] == _BACKREF
  1157.     || r->tokens[i] >= _SET)
  1158.       {
  1159.     copy(&r->follows[i], &merged);
  1160.     epsclosure(&merged, r);
  1161.     if (r->follows[i].nelem < merged.nelem)
  1162.       REALLOC(r->follows[i].elems, _position, merged.nelem);
  1163.     copy(&merged, &r->follows[i]);
  1164.       }
  1165.  
  1166.   /* Get the epsilon closure of the firstpos of the regexp.  The result will
  1167.      be the set of positions of state 0. */
  1168.   merged.nelem = 0;
  1169.   for (i = 0; i < nfirstpos[-1]; ++i)
  1170.     insert(firstpos[i], &merged);
  1171.   epsclosure(&merged, r);
  1172.  
  1173.   /* Check if any of the positions of state 0 will want newline context. */
  1174.   wants_newline = 0;
  1175.   for (i = 0; i < merged.nelem; ++i)
  1176.     if (_PREV_NEWLINE_DEPENDENT(merged.elems[i].constraint))
  1177.       wants_newline = 1;
  1178.  
  1179.   /* Build the initial state. */
  1180.   r->salloc = 1;
  1181.   r->sindex = 0;
  1182.   MALLOC(r->states, _dfa_state, r->salloc);
  1183.   state_index(r, &merged, wants_newline, 0);
  1184.  
  1185.   free(o_nullable);
  1186.   free(o_nfirst);
  1187.   free(o_firstpos);
  1188.   free(o_nlast);
  1189.   free(o_lastpos);
  1190.   free(nalloc);
  1191.   free(merged.elems);
  1192. }
  1193.  
  1194. /* Find, for each character, the transition out of state s of r, and store
  1195.    it in the appropriate slot of trans.
  1196.  
  1197.    We divide the positions of s into groups (positions can appear in more
  1198.    than one group).  Each group is labeled with a set of characters that
  1199.    every position in the group matches (taking into account, if necessary,
  1200.    preceding context information of s).  For each group, find the union
  1201.    of the its elements' follows.  This set is the set of positions of the
  1202.    new state.  For each character in the group's label, set the transition
  1203.    on this character to be to a state corresponding to the set's positions,
  1204.    and its associated backward context information, if necessary.
  1205.  
  1206.    If we are building a searching matcher, we include the positions of state
  1207.    0 in every state.
  1208.  
  1209.    The collection of groups is constructed by building an equivalence-class
  1210.    partition of the positions of s.
  1211.  
  1212.    For each position, find the set of characters C that it matches.  Eliminate
  1213.    any characters from C that fail on grounds of backward context.
  1214.  
  1215.    Search through the groups, looking for a group whose label L has nonempty
  1216.    intersection with C.  If L - C is nonempty, create a new group labeled
  1217.    L - C and having the same positions as the current group, and set L to
  1218.    the intersection of L and C.  Insert the position in this group, set
  1219.    C = C - L, and resume scanning.
  1220.  
  1221.    If after comparing with every group there are characters remaining in C,
  1222.    create a new group labeled with the characters of C and insert this
  1223.    position in that group. */
  1224. void
  1225. regstate(s, r, trans)
  1226.      int s;
  1227.      struct regexp *r;
  1228.      int trans[];
  1229. {
  1230.   _position_set grps[_NOTCHAR];    /* As many as will ever be needed. */
  1231.   _charset labels[_NOTCHAR];    /* Labels corresponding to the groups. */
  1232.   int ngrps = 0;        /* Number of groups actually used. */
  1233.   _position pos;        /* Current position being considered. */
  1234.   _charset matches;        /* Set of matching characters. */
  1235.   int matchesf;            /* True if matches is nonempty. */
  1236.   _charset intersect;        /* Intersection with some label set. */
  1237.   int intersectf;        /* True if intersect is nonempty. */
  1238.   _charset leftovers;        /* Stuff in the label that didn't match. */
  1239.   int leftoversf;        /* True if leftovers is nonempty. */
  1240.   static _charset letters;    /* Set of characters considered letters. */
  1241.   static _charset newline;    /* Set of characters that aren't newline. */
  1242.   _position_set follows;    /* Union of the follows of some group. */
  1243.   _position_set tmp;        /* Temporary space for merging sets. */
  1244.   int state;            /* New state. */
  1245.   int wants_newline;        /* New state wants to know newline context. */
  1246.   int state_newline;        /* New state on a newline transition. */
  1247.   int wants_letter;        /* New state wants to know letter context. */
  1248.   int state_letter;        /* New state on a letter transition. */
  1249.   static initialized;        /* Flag for static initialization. */
  1250.   int i, j, k;
  1251.  
  1252.   /* Initialize the set of letters, if necessary. */
  1253.   if (! initialized)
  1254.     {
  1255.       initialized = 1;
  1256.       for (i = 0; i < _NOTCHAR; ++i)
  1257.     if (ISALNUM(i))
  1258.       setbit(i, letters);
  1259.       setbit('\r', newline); /*newline changed */
  1260.     }
  1261.  
  1262.   zeroset(matches);
  1263.  
  1264.   for (i = 0; i < r->states[s].elems.nelem; ++i)
  1265.     {
  1266.       pos = r->states[s].elems.elems[i];
  1267.       if (r->tokens[pos.index] >= 0 && r->tokens[pos.index] < _NOTCHAR)
  1268.     setbit(r->tokens[pos.index], matches);
  1269.       else if (r->tokens[pos.index] >= _SET)
  1270.     copyset(r->charsets[r->tokens[pos.index] - _SET], matches);
  1271.       else
  1272.     continue;
  1273.  
  1274.       /* Some characters may need to be climinated from matches because
  1275.      they fail in the current context. */
  1276.       if (pos.constraint != 0xff)
  1277.     {
  1278.       if (! _MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1279.                      r->states[s].newline, 1))
  1280.         clrbit('\r', matches);   /* newline changed */
  1281.       if (! _MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1282.                      r->states[s].newline, 0))
  1283.         for (j = 0; j < _CHARSET_INTS; ++j)
  1284.           matches[j] &= newline[j];
  1285.       if (! _MATCHES_LETTER_CONTEXT(pos.constraint,
  1286.                     r->states[s].letter, 1))
  1287.         for (j = 0; j < _CHARSET_INTS; ++j)
  1288.           matches[j] &= ~letters[j];
  1289.       if (! _MATCHES_LETTER_CONTEXT(pos.constraint,
  1290.                     r->states[s].letter, 0))
  1291.         for (j = 0; j < _CHARSET_INTS; ++j)
  1292.           matches[j] &= letters[j];
  1293.  
  1294.       /* If there are no characters left, there's no point in going on. */
  1295.       for (j = 0; j < _CHARSET_INTS && !matches[j]; ++j)
  1296.         ;
  1297.       if (j == _CHARSET_INTS)
  1298.         continue;
  1299.     }
  1300.  
  1301.       for (j = 0; j < ngrps; ++j)
  1302.     {
  1303.       /* If matches contains a single character only, and the current
  1304.          group's label doesn't contain that character, go on to the
  1305.          next group. */
  1306.       if (r->tokens[pos.index] >= 0 && r->tokens[pos.index] < _NOTCHAR
  1307.           && !tstbit(r->tokens[pos.index], labels[j]))
  1308.         continue;
  1309.  
  1310.       /* Check if this group's label has a nonempty intersection with
  1311.          matches. */
  1312.       intersectf = 0;
  1313.       for (k = 0; k < _CHARSET_INTS; ++k)
  1314.         (intersect[k] = matches[k] & labels[j][k]) ? intersectf = 1 : 0;
  1315.       if (! intersectf)
  1316.         continue;
  1317.  
  1318.       /* It does; now find the set differences both ways. */
  1319.       leftoversf = matchesf = 0;
  1320.       for (k = 0; k < _CHARSET_INTS; ++k)
  1321.         {
  1322.           /* Even an optimizing compiler can't know this for sure. */
  1323.           int match = matches[k], label = labels[j][k];
  1324.  
  1325.           (leftovers[k] = ~match & label) ? leftoversf = 1 : 0;
  1326.           (matches[k] = match & ~label) ? matchesf = 1 : 0;
  1327.         }
  1328.  
  1329.       /* If there were leftovers, create a new group labeled with them. */
  1330.       if (leftoversf)
  1331.         {
  1332.           copyset(leftovers, labels[ngrps]);
  1333.           copyset(intersect, labels[j]);
  1334.           MALLOC(grps[ngrps].elems, _position, r->nleaves);
  1335.           copy(&grps[j], &grps[ngrps]);
  1336.           ++ngrps;
  1337.         }
  1338.  
  1339.       /* Put the position in the current group.  Note that there is no
  1340.          reason to call insert() here. */
  1341.       grps[j].elems[grps[j].nelem++] = pos;
  1342.  
  1343.       /* If every character matching the current position has been
  1344.          accounted for, we're done. */
  1345.       if (! matchesf)
  1346.         break;
  1347.     }
  1348.  
  1349.       /* If we've passed the last group, and there are still characters
  1350.      unaccounted for, then we'll have to create a new group. */
  1351.       if (j == ngrps)
  1352.     {
  1353.       copyset(matches, labels[ngrps]);
  1354.       zeroset(matches);
  1355.       MALLOC(grps[ngrps].elems, _position, r->nleaves);
  1356.       grps[ngrps].nelem = 1;
  1357.       grps[ngrps].elems[0] = pos;
  1358.       ++ngrps;
  1359.     }
  1360.     }
  1361.  
  1362.   MALLOC(follows.elems, _position, r->nleaves);
  1363.   MALLOC(tmp.elems, _position, r->nleaves);
  1364.  
  1365.   /* If we are a searching matcher, the default transition is to a state
  1366.      containing the positions of state 0, otherwise the default transition
  1367.      is to fail miserably. */
  1368.   if (r->searchflag)
  1369.     {
  1370.       wants_newline = 0;
  1371.       wants_letter = 0;
  1372.       for (i = 0; i < r->states[0].elems.nelem; ++i)
  1373.     {
  1374.       if (_PREV_NEWLINE_DEPENDENT(r->states[0].elems.elems[i].constraint))
  1375.         wants_newline = 1;
  1376.       if (_PREV_LETTER_DEPENDENT(r->states[0].elems.elems[i].constraint))
  1377.         wants_letter = 1;
  1378.     }
  1379.       copy(&r->states[0].elems, &follows);
  1380.       state = state_index(r, &follows, 0, 0);
  1381.       if (wants_newline)
  1382.     state_newline = state_index(r, &follows, 1, 0);
  1383.       else
  1384.     state_newline = state;
  1385.       if (wants_letter)
  1386.     state_letter = state_index(r, &follows, 0, 1);
  1387.       else
  1388.     state_letter = state;
  1389.       for (i = 0; i < _NOTCHAR; ++i)
  1390.     if (i == '\r')   /* newline changed */
  1391.       trans[i] = state_newline;
  1392.     else if (ISALNUM(i))
  1393.       trans[i] = state_letter;
  1394.     else
  1395.       trans[i] = state;
  1396.     }
  1397.   else
  1398.     for (i = 0; i < _NOTCHAR; ++i)
  1399.       trans[i] = -1;
  1400.  
  1401.   for (i = 0; i < ngrps; ++i)
  1402.     {
  1403.       follows.nelem = 0;
  1404.  
  1405.       /* Find the union of the follows of the positions of the group.
  1406.      This is a hideously inefficient loop.  Fix it someday. */
  1407.       for (j = 0; j < grps[i].nelem; ++j)
  1408.     for (k = 0; k < r->follows[grps[i].elems[j].index].nelem; ++k)
  1409.       insert(r->follows[grps[i].elems[j].index].elems[k], &follows);
  1410.  
  1411.       /* If we are building a searching matcher, throw in the positions
  1412.      of state 0 as well. */
  1413.       if (r->searchflag)
  1414.     for (j = 0; j < r->states[0].elems.nelem; ++j)
  1415.       insert(r->states[0].elems.elems[j], &follows);
  1416.  
  1417.       /* Find out if the new state will want any context information. */
  1418.       wants_newline = 0;
  1419.       if (tstbit('\r', labels[i]))  /* newline changed */
  1420.     for (j = 0; j < follows.nelem; ++j)
  1421.       if (_PREV_NEWLINE_DEPENDENT(follows.elems[j].constraint))
  1422.         wants_newline = 1;
  1423.  
  1424.       wants_letter = 0;
  1425.       for (j = 0; j < _CHARSET_INTS; ++j)
  1426.     if (labels[i][j] & letters[j])
  1427.       break;
  1428.       if (j < _CHARSET_INTS)
  1429.     for (j = 0; j < follows.nelem; ++j)
  1430.       if (_PREV_LETTER_DEPENDENT(follows.elems[j].constraint))
  1431.         wants_letter = 1;
  1432.  
  1433.       /* Find the state(s) corresponding to the union of the follows. */
  1434.       state = state_index(r, &follows, 0, 0);
  1435.       if (wants_newline)
  1436.     state_newline = state_index(r, &follows, 1, 0);
  1437.       else
  1438.     state_newline = state;
  1439.       if (wants_letter)
  1440.     state_letter = state_index(r, &follows, 0, 1);
  1441.       else
  1442.     state_letter = state;
  1443.  
  1444.       /* Set the transitions for each character in the current label. */
  1445.       for (j = 0; j < _CHARSET_INTS; ++j)
  1446.     for (k = 0; k < INTBITS; ++k)
  1447.       if (labels[i][j] & 1 << k)
  1448.         {
  1449.           int c = j * INTBITS + k;
  1450.  
  1451.           if (c == '\r')  /* newline changed */
  1452.         trans[c] = state_newline;
  1453.           else if (ISALNUM(c))
  1454.         trans[c] = state_letter;
  1455.           else if (c < _NOTCHAR)
  1456.         trans[c] = state;
  1457.         }
  1458.     }
  1459.  
  1460.   for (i = 0; i < ngrps; ++i)
  1461.     free(grps[i].elems);
  1462.   free(follows.elems);
  1463.   free(tmp.elems);
  1464. }
  1465.  
  1466. /* Some routines for manipulating a compiled regexp's transition tables.
  1467.    Each state may or may not have a transition table; if it does, and it
  1468.    is a non-accepting state, then r->trans[state] points to its table.
  1469.    If it is an accepting state then r->fails[state] points to its table.
  1470.    If it has no table at all, then r->trans[state] is NULL.
  1471.    TODO: Improve this comment, get rid of the unnecessary redundancy. */
  1472.  
  1473. static void
  1474. build_state(s, r)
  1475.      int s;
  1476.      struct regexp *r;
  1477. {
  1478.   int *trans;            /* The new transition table. */
  1479.   int i;
  1480.  
  1481.   /* Set an upper limit on the number of transition tables that will ever
  1482.      exist at once.  1024 is arbitrary.  The idea is that the frequently
  1483.      used transition tables will be quickly rebuilt, whereas the ones that
  1484.      were only needed once or twice will be cleared away. */
  1485.   if (r->trcount >= 1024)
  1486.     {
  1487.       for (i = 0; i < r->tralloc; ++i)
  1488.     if (r->trans[i])
  1489.       {
  1490.         free((ptr_t) r->trans[i]);
  1491.         r->trans[i] = NULL;
  1492.       }
  1493.     else if (r->fails[i])
  1494.       {
  1495.         free((ptr_t) r->fails[i]);
  1496.         r->fails[i] = NULL;
  1497.       }
  1498.       r->trcount = 0;
  1499.     }
  1500.  
  1501.   ++r->trcount;
  1502.  
  1503.   /* Set up the success bits for this state. */
  1504.   r->success[s] = 0;
  1505.   if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 1, r->states[s].letter, 0,
  1506.       s, *r))
  1507.     r->success[s] |= 4;
  1508.   if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 0, r->states[s].letter, 1,
  1509.       s, *r))
  1510.     r->success[s] |= 2;
  1511.   if (ACCEPTS_IN_CONTEXT(r->states[s].newline, 0, r->states[s].letter, 0,
  1512.       s, *r))
  1513.     r->success[s] |= 1;
  1514.  
  1515.   MALLOC(trans, int, _NOTCHAR);
  1516.   regstate(s, r, trans);
  1517.  
  1518.   /* Now go through the new transition table, and make sure that the trans
  1519.      and fail arrays are allocated large enough to hold a pointer for the
  1520.      largest state mentioned in the table. */
  1521.   for (i = 0; i < _NOTCHAR; ++i)
  1522.     if (trans[i] >= r->tralloc)
  1523.       {
  1524.     int oldalloc = r->tralloc;
  1525.  
  1526.     while (trans[i] >= r->tralloc)
  1527.       r->tralloc *= 2;
  1528.     REALLOC(r->realtrans, int *, r->tralloc + 1);
  1529.     r->trans = r->realtrans + 1;
  1530.     REALLOC(r->fails, int *, r->tralloc);
  1531.     REALLOC(r->success, int, r->tralloc);
  1532.     REALLOC(r->newlines, int, r->tralloc);
  1533.     while (oldalloc < r->tralloc)
  1534.       {
  1535.         r->trans[oldalloc] = NULL;
  1536.         r->fails[oldalloc++] = NULL;
  1537.       }
  1538.       }
  1539.  
  1540.   /* Keep the newline transition in a special place so we can use it as
  1541.      a sentinel. */
  1542.   r->newlines[s] = trans['\r'];  /* newline changed */
  1543.   trans['\r'] = -1;  /* newline changed */
  1544.  
  1545.   if (ACCEPTING(s, *r))
  1546.     r->fails[s] = trans;
  1547.   else
  1548.     r->trans[s] = trans;
  1549. }
  1550.  
  1551. static void
  1552. build_state_zero(r)
  1553.      struct regexp *r;
  1554. {
  1555.   r->tralloc = 1;
  1556.   r->trcount = 0;
  1557.   CALLOC(r->realtrans, int *, r->tralloc + 1);
  1558.   r->trans = r->realtrans + 1;
  1559.   CALLOC(r->fails, int *, r->tralloc);
  1560.   MALLOC(r->success, int, r->tralloc);
  1561.   MALLOC(r->newlines, int, r->tralloc);
  1562.   build_state(0, r);
  1563. }
  1564.  
  1565. /* Search through a buffer looking for a match to the given struct regexp.
  1566.    Find the first occurrence of a string matching the regexp in the buffer,
  1567.    and the shortest possible version thereof.  Return a pointer to the first
  1568.    character after the match, or NULL if none is found.  Begin points to
  1569.    the beginning of the buffer, and end points to the first character after
  1570.    its end.  We store a newline in *end to act as a sentinel, so end had
  1571.    better point somewhere valid.  Newline is a flag indicating whether to
  1572.    allow newlines to be in the matching string.  If count is non-
  1573.    NULL it points to a place we're supposed to increment every time we
  1574.    see a newline.  Finally, if backref is non-NULL it points to a place
  1575.    where we're supposed to store a 1 if backreferencing happened and the
  1576.    match needs to be verified by a backtracking matcher.  Otherwise
  1577.    we store a 0 in *backref. */
  1578. char *
  1579. regexecute(r, begin, end, newline, count, backref)
  1580.      struct regexp *r;
  1581.      char *begin;
  1582.      char *end;
  1583.      int newline;
  1584.      int *count;
  1585.      int *backref;
  1586. {
  1587.   register s, s1, tmp;        /* Current state. */
  1588.   register unsigned char *p;    /* Current input character. */
  1589.   register **trans, *t;        /* Copy of r->trans so it can be optimized
  1590.                    into a register. */
  1591.   static sbit[_NOTCHAR];    /* Table for anding with r->success. */
  1592.   static sbit_init;
  1593.  
  1594.   if (! sbit_init)
  1595.     {
  1596.       int i;
  1597.  
  1598.       sbit_init = 1;
  1599.       for (i = 0; i < _NOTCHAR; ++i)
  1600.     if (i == '\r')  /* newline changed */
  1601.       sbit[i] = 4;
  1602.     else if (ISALNUM(i))
  1603.       sbit[i] = 2;
  1604.     else
  1605.       sbit[i] = 1;
  1606.     }
  1607.  
  1608.   if (! r->tralloc)
  1609.     build_state_zero(r);
  1610.  
  1611.   s = 0;
  1612.   p = (unsigned char *) begin;
  1613.   trans = r->trans;
  1614.   *end = '\r';  /* newline changed */
  1615.  
  1616.   for (;;)
  1617.     {
  1618.       /* The dreaded inner loop. */
  1619.       if (t = trans[s])
  1620.     do
  1621.       {
  1622.         s1 = t[*p++];
  1623.         if (! (t = trans[s1]))
  1624.           goto last_was_s;
  1625.         s = t[*p++];
  1626.       }
  1627.         while (t = trans[s]);
  1628.       goto last_was_s1;
  1629.     last_was_s:
  1630.       tmp = s, s = s1, s1 = tmp;
  1631.     last_was_s1:
  1632.  
  1633.       if (s >= 0 && p <= (unsigned char *) end && r->fails[s])
  1634.     {
  1635.       if (r->success[s] & sbit[*p])
  1636.         {
  1637.           if (backref)
  1638.         if (r->states[s].backref)
  1639.           *backref = 1;
  1640.         else
  1641.           *backref = 0;
  1642.           return (char *) p;
  1643.         }
  1644.  
  1645.       s1 = s;
  1646.       s = r->fails[s][*p++];
  1647.       continue;
  1648.     }
  1649.  
  1650.       /* If the previous character was a newline, count it. */
  1651.       if (count && (char *) p <= end && p[-1] == '\r')  /* newline changed */
  1652.     ++*count;
  1653.  
  1654.       /* Check if we've run off the end of the buffer. */
  1655.       if ((char *) p >= end)
  1656.     return NULL;
  1657.  
  1658.       if (s >= 0)
  1659.     {
  1660.       build_state(s, r);
  1661.       trans = r->trans;
  1662.       continue;
  1663.     }
  1664.  
  1665.       if (p[-1] == '\r' && newline)  /* newline changed */
  1666.     {
  1667.       s = r->newlines[s1];
  1668.       continue;
  1669.     }
  1670.  
  1671.       s = 0;
  1672.     }
  1673. }
  1674.  
  1675. /* Initialize the components of a regexp that the other routines don't
  1676.    initialize for themselves. */
  1677. void
  1678. reginit(r)
  1679.      struct regexp *r;
  1680. {
  1681.   r->calloc = 1;
  1682.   MALLOC(r->charsets, _charset, r->calloc);
  1683.   r->cindex = 0;
  1684.  
  1685.   r->talloc = 1;
  1686.   MALLOC(r->tokens, _token, r->talloc);
  1687.   r->tindex = r->depth = r->nleaves = r->nregexps = 0;
  1688.  
  1689.   r->searchflag = 0;
  1690.   r->tralloc = 0;
  1691. }
  1692.  
  1693. /* Parse and analyze a single string of the given length. */
  1694. void
  1695. regcompile(s, len, r, searchflag)
  1696.      const char *s;
  1697.      size_t len;
  1698.      struct regexp *r;
  1699.      int searchflag;
  1700. {
  1701.   if (case_fold)    /* dummy folding in service of regmust() */
  1702.     {
  1703.       char *copy;
  1704.       int i;
  1705.  
  1706.       copy = malloc(len);
  1707.       if (!copy)
  1708.     regerror("out of memory");
  1709.       
  1710.       /* This is a complete kludge and could potentially break
  1711.      \<letter> escapes . . . */
  1712.       case_fold = 0;
  1713.       for (i = 0; i < len; ++i)
  1714.     if (ISUPPER(s[i]))
  1715.       copy[i] = tolower(s[i]);
  1716.     else
  1717.       copy[i] = s[i];
  1718.  
  1719.       reginit(r);
  1720.       r->mustn = 0;
  1721.       r->must[0] = '\0';
  1722.       regparse(copy, len, r);
  1723.       free(copy);
  1724.       regmust(r);
  1725.       reganalyze(r, searchflag);
  1726.       case_fold = 1;
  1727.       reginit(r);
  1728.       regparse(s, len, r);
  1729.       reganalyze(r, searchflag);
  1730.     }
  1731.   else
  1732.     {
  1733.         reginit(r);
  1734.         regparse(s, len, r);
  1735.         regmust(r);
  1736.         reganalyze(r, searchflag);
  1737.     }
  1738. }
  1739.  
  1740. /* Free the storage held by the components of a regexp. */
  1741. void
  1742. regfree(r)
  1743.      struct regexp *r;
  1744. {
  1745.   int i;
  1746.  
  1747.   free((ptr_t) r->charsets);
  1748.   free((ptr_t) r->tokens);
  1749.   for (i = 0; i < r->sindex; ++i)
  1750.     free((ptr_t) r->states[i].elems.elems);
  1751.   free((ptr_t) r->states);
  1752.   for (i = 0; i < r->tindex; ++i)
  1753.     if (r->follows[i].elems)
  1754.       free((ptr_t) r->follows[i].elems);
  1755.   free((ptr_t) r->follows);
  1756.   for (i = 0; i < r->tralloc; ++i)
  1757.     if (r->trans[i])
  1758.       free((ptr_t) r->trans[i]);
  1759.     else if (r->fails[i])
  1760.       free((ptr_t) r->fails[i]);
  1761.   free((ptr_t) r->realtrans);
  1762.   free((ptr_t) r->fails);
  1763.   free((ptr_t) r->newlines);
  1764. }
  1765.  
  1766. /*
  1767. Having found the postfix representation of the regular expression,
  1768. try to find a long sequence of characters that must appear in any line
  1769. containing the r.e.
  1770. Finding a "longest" sequence is beyond the scope here;
  1771. we take an easy way out and hope for the best.
  1772. (Take "(ab|a)b"--please.)
  1773.  
  1774. We do a bottom-up calculation of sequences of characters that must appear
  1775. in matches of r.e.'s represented by trees rooted at the nodes of the postfix
  1776. representation:
  1777.     sequences that must appear at the left of the match ("left")
  1778.     sequences that must appear at the right of the match ("right")
  1779.     lists of sequences that must appear somewhere in the match ("in")
  1780.     sequences that must constitute the match ("is")
  1781. When we get to the root of the tree, we use one of the longest of its
  1782. calculated "in" sequences as our answer.  The sequence we find is returned in
  1783. r->must (where "r" is the single argument passed to "regmust");
  1784. the length of the sequence is returned in r->mustn.
  1785.  
  1786. The sequences calculated for the various types of node (in pseudo ANSI c)
  1787. are shown below.  "p" is the operand of unary operators (and the left-hand
  1788. operand of binary operators); "q" is the right-hand operand of binary operators
  1789. .
  1790. "ZERO" means "a zero-length sequence" below.
  1791.  
  1792. Type    left        right        is        in
  1793. ----    ----        -----        --        --
  1794. char c    # c        # c        # c        # c
  1795.  
  1796. SET    ZERO        ZERO        ZERO        ZERO
  1797.  
  1798. STAR    ZERO        ZERO        ZERO        ZERO
  1799.  
  1800. QMARK    ZERO        ZERO        ZERO        ZERO
  1801.  
  1802. PLUS    p->left        p->right    ZERO        p->in
  1803.  
  1804. CAT    (p->is==ZERO)?    (q->is==ZERO)?    (p->is!=ZERO &&    p->in plus
  1805.     p->left :    q->right :    q->is!=ZERO) ?    q->in plus
  1806.     p->is##q->left    p->right##q->is    p->is##q->is :    p->right##q->left
  1807.                     ZERO
  1808.  
  1809. OR    longest common    longest common    (do p->is and    substrings common to
  1810.     leading        trailing    q->is have same    p->in and q->in
  1811.     (sub)sequence    (sub)sequence    length and    
  1812.     of p->left    of p->right    content) ?    
  1813.     and q->left    and q->right    p->is : NULL    
  1814.  
  1815. If there's anything else we recognize in the tree, all four sequences get set
  1816. to zero-length sequences.  If there's something we don't recognize in the tree,
  1817. we just return a zero-length sequence.
  1818.  
  1819. Break ties in favor of infrequent letters (choosing 'zzz' in preference to
  1820. 'aaa')?
  1821.  
  1822. And. . .is it here or someplace that we might ponder "optimizations" such as
  1823.     egrep 'psi|epsilon'    ->    egrep 'psi'
  1824.     egrep 'pepsi|epsilon'    ->    egrep 'epsi'
  1825.                     (Yes, we now find "epsi" as a "string
  1826.                     that must occur", but we might also
  1827.                     simplify the *entire* r.e. being sought
  1828. )
  1829.     grep '[c]'        ->    grep 'c'
  1830.     grep '(ab|a)b'        ->    grep 'ab'
  1831.     grep 'ab*'        ->    grep 'a'
  1832.     grep 'a*b'        ->    grep 'b'
  1833. There are several issues:
  1834.     Is optimization easy (enough)?
  1835.  
  1836.     Does optimization actually accomplish anything,
  1837.     or is the automaton you get from "psi|epsilon" (for example)
  1838.     the same as the one you get from "psi" (for example)?
  1839.  
  1840.     Are optimizable r.e.'s likely to be used in real-life situations
  1841.     (something like 'ab*' is probably unlikely; something like is
  1842.     'psi|epsilon' is likelier)?
  1843. */
  1844.  
  1845. static char *
  1846. icatalloc(old, new)
  1847. char *    old;
  1848. char *    new;
  1849. {
  1850.     register char *    result;
  1851.     register int    oldsize, newsize;
  1852.  
  1853.     newsize = (new == NULL) ? 0 : strlen(new);
  1854.     if (old == NULL)
  1855.         oldsize = 0;
  1856.     else if (newsize == 0)
  1857.         return old;
  1858.     else    oldsize = strlen(old);
  1859.     if (old == NULL)
  1860.         result = (char *) malloc(newsize + 1);
  1861.     else    result = (char *) realloc((void *) old, oldsize + newsize + 1);
  1862.     if (result != NULL && new != NULL)
  1863.         (void) strcpy(result + oldsize, new);
  1864.     return result;
  1865. }
  1866.  
  1867. static char *
  1868. icpyalloc(string)
  1869. const char *    string;
  1870. {
  1871.     return icatalloc((char *) NULL, (void *)string);
  1872. }
  1873.  
  1874. static char *
  1875. istrstr(lookin, lookfor)
  1876. char *        lookin;
  1877. register char *    lookfor;
  1878. {
  1879.     register char *    cp;
  1880.     register int    len;
  1881.  
  1882.     len = strlen(lookfor);
  1883.     for (cp = lookin; *cp != '\0'; ++cp)
  1884.         if (strncmp(cp, lookfor, len) == 0)
  1885.             return cp;
  1886.     return NULL;
  1887. }
  1888.  
  1889. static void
  1890. ifree(cp)
  1891. char *    cp;
  1892. {
  1893.     if (cp != NULL)
  1894.         free(cp);
  1895. }
  1896.  
  1897. static void
  1898. freelist(cpp)
  1899. register char **    cpp;
  1900. {
  1901.     register int    i;
  1902.  
  1903.     if (cpp == NULL)
  1904.         return;
  1905.     for (i = 0; cpp[i] != NULL; ++i) {
  1906.         free(cpp[i]);
  1907.         cpp[i] = NULL;
  1908.     }
  1909. }
  1910.  
  1911. static char **
  1912. enlist(cpp, new, len)
  1913. int len;
  1914. register char **    cpp;
  1915. register char *        new;
  1916. {
  1917.     register int    i, j;
  1918.  
  1919.     if (cpp == NULL)
  1920.         return NULL;
  1921.     if ((new = icpyalloc(new)) == NULL) {
  1922.         freelist(cpp);
  1923.         return NULL;
  1924.     }
  1925.     new[len] = '\0';
  1926.     /*
  1927.     ** Is there already something in the list that's new (or longer)?
  1928.     */
  1929.     for (i = 0; cpp[i] != NULL; ++i)
  1930.         if (istrstr(cpp[i], new) != NULL) {
  1931.             free(new);
  1932.             return cpp;
  1933.         }
  1934.     /*
  1935.     ** Eliminate any obsoleted strings.
  1936.     */
  1937.     j = 0;
  1938.     while (cpp[j] != NULL)
  1939.         if (istrstr(new, cpp[j]) == NULL)
  1940.             ++j;
  1941.         else {
  1942.             free(cpp[j]);
  1943.             if (--i == j)
  1944.                 break;
  1945.             cpp[j] = cpp[i];
  1946.         }
  1947.     /*
  1948.     ** Add the new string.
  1949.     */
  1950.     cpp = (char **) realloc((char *) cpp, (i + 2) * sizeof *cpp);
  1951.     if (cpp == NULL)
  1952.         return NULL;
  1953.     cpp[i] = new;
  1954.     cpp[i + 1] = NULL;
  1955.     return cpp;
  1956. }
  1957.  
  1958. /*
  1959. ** Given pointers to two strings,
  1960. ** return a pointer to an allocated list of their distinct common substrings.
  1961. ** Return NULL if something seems wild.
  1962. */
  1963.  
  1964. static char **
  1965. comsubs(left, right)
  1966. char *    left;
  1967. char *    right;
  1968. {
  1969.     register char **    cpp;
  1970.     register char *        lcp;
  1971.     register char *        rcp;
  1972.     register int        i, len;
  1973.  
  1974.     if (left == NULL || right == NULL)
  1975.         return NULL;
  1976.     cpp = (char **) malloc(sizeof *cpp);
  1977.     if (cpp == NULL)
  1978.         return NULL;
  1979.     cpp[0] = NULL;
  1980.     for (lcp = left; *lcp != '\0'; ++lcp) {
  1981.         len = 0;
  1982.         rcp = strchr(right, *lcp);
  1983.         while (rcp != NULL) {
  1984.             for (i = 1; lcp[i] != '\0' && lcp[i] == rcp[i]; ++i)
  1985.                 ;
  1986.             if (i > len)
  1987.                 len = i;
  1988.             rcp = strchr(rcp + 1, *lcp);
  1989.         }
  1990.         if (len == 0)
  1991.             continue;
  1992.         if ((cpp = enlist(cpp, lcp, len)) == NULL)
  1993.             break;
  1994.     }
  1995.     return cpp;
  1996. }
  1997.  
  1998. static char **
  1999. addlists(old, new)
  2000. char **    old;
  2001. char **    new;
  2002. {
  2003.     register int    i;
  2004.  
  2005.     if (old == NULL || new == NULL)
  2006.         return NULL;
  2007.     for (i = 0; new[i] != NULL; ++i) {
  2008.         old = enlist(old, new[i], strlen(new[i]));
  2009.         if (old == NULL)
  2010.             break;
  2011.     }
  2012.     return old;
  2013. }
  2014.  
  2015. /*
  2016. ** Given two lists of substrings,
  2017. ** return a new list giving substrings common to both.
  2018. */
  2019.  
  2020. static char **
  2021. inboth(left, right)
  2022. char **    left;
  2023. char **    right;
  2024. {
  2025.     register char **    both;
  2026.     register char **    temp;
  2027.     register int        lnum, rnum;
  2028.  
  2029.     if (left == NULL || right == NULL)
  2030.         return NULL;
  2031.     both = (char **) malloc(sizeof *both);
  2032.     if (both == NULL)
  2033.         return NULL;
  2034.     both[0] = NULL;
  2035.     for (lnum = 0; left[lnum] != NULL; ++lnum) {
  2036.         for (rnum = 0; right[rnum] != NULL; ++rnum) {
  2037.             temp = comsubs(left[lnum], right[rnum]);
  2038.             if (temp == NULL) {
  2039.                 freelist(both);
  2040.                 return NULL;
  2041.             }
  2042.             both = addlists(both, temp);
  2043.             freelist(temp);
  2044.             if (both == NULL)
  2045.                 return NULL;
  2046.         }
  2047.     }
  2048.     return both;
  2049. }
  2050.  
  2051. typedef struct {
  2052.     char **    in;
  2053.     char *    left;
  2054.     char *    right;
  2055.     char *    is;
  2056. } must;
  2057.  
  2058. static void
  2059. resetmust(mp)
  2060. register must *    mp;
  2061. {
  2062.     mp->left[0] = mp->right[0] = mp->is[0] = '\0';
  2063.     freelist(mp->in);
  2064. }
  2065.  
  2066. static void
  2067. regmust(r)
  2068. register struct regexp *    r;
  2069. {
  2070.     register must *        musts;
  2071.     register must *        mp;
  2072.     register char *        result;
  2073.     register int        ri;
  2074.     register int        i;
  2075.     register _token        t;
  2076.     static must        must0;
  2077.  
  2078.     reg->mustn = 0;
  2079.     reg->must[0] = '\0';
  2080.     musts = (must *) malloc((reg->tindex + 1) * sizeof *musts);
  2081.     if (musts == NULL)
  2082.         return;
  2083.     mp = musts;
  2084.     for (i = 0; i <= reg->tindex; ++i)
  2085.         mp[i] = must0;
  2086.     for (i = 0; i <= reg->tindex; ++i) {
  2087.         mp[i].in = (char **) malloc(sizeof *mp[i].in);
  2088.         mp[i].left = malloc(2);
  2089.         mp[i].right = malloc(2);
  2090.         mp[i].is = malloc(2);
  2091.         if (mp[i].in == NULL || mp[i].left == NULL ||
  2092.             mp[i].right == NULL || mp[i].is == NULL)
  2093.                 goto done;
  2094.         mp[i].left[0] = mp[i].right[0] = mp[i].is[0] = '\0';
  2095.         mp[i].in[0] = NULL;
  2096.     }
  2097.     result = "";
  2098.     for (ri = 0; ri < reg->tindex; ++ri) {
  2099.         switch (t = reg->tokens[ri]) {
  2100.         case _ALLBEGLINE:
  2101.         case _ALLENDLINE:
  2102.         case _LPAREN:
  2103.         case _RPAREN:
  2104.             goto done;        /* "cannot happen" */
  2105.         case _EMPTY:
  2106.         case _BEGLINE:
  2107.         case _ENDLINE:
  2108.         case _BEGWORD:
  2109.         case _ENDWORD:
  2110.         case _LIMWORD:
  2111.         case _NOTLIMWORD:
  2112.         case _BACKREF:
  2113.             resetmust(mp);
  2114.             break;
  2115.         case _STAR:
  2116.         case _QMARK:
  2117.             if (mp <= musts)
  2118.                 goto done;    /* "cannot happen" */
  2119.             --mp;
  2120.             resetmust(mp);
  2121.             break;
  2122.         case _OR:
  2123.             if (mp < &musts[2])
  2124.                 goto done;    /* "cannot happen" */
  2125.             {
  2126.                 register char **    new;
  2127.                 register must *        lmp;
  2128.                 register must *        rmp;
  2129.                 register int        j, ln, rn, n;
  2130.  
  2131.                 rmp = --mp;
  2132.                 lmp = --mp;
  2133.                 /* Guaranteed to be.  Unlikely, but. . . */
  2134.                 if (strcmp(lmp->is, rmp->is) != 0)
  2135.                     lmp->is[0] = '\0';
  2136.                 /* Left side--easy */
  2137.                 i = 0;
  2138.                 while (lmp->left[i] != '\0' &&
  2139.                     lmp->left[i] == rmp->left[i])
  2140.                         ++i;
  2141.                 lmp->left[i] = '\0';
  2142.                 /* Right side */
  2143.                 ln = strlen(lmp->right);
  2144.                 rn = strlen(rmp->right);
  2145.                 n = ln;
  2146.                 if (n > rn)
  2147.                     n = rn;
  2148.                 for (i = 0; i < n; ++i)
  2149.                     if (lmp->right[ln - i - 1] !=
  2150.                         rmp->right[rn - i - 1])
  2151.                         break;
  2152.                 for (j = 0; j < i; ++j)
  2153.                     lmp->right[j] =
  2154.                         lmp->right[(ln - i) + j];
  2155.                 lmp->right[j] = '\0';
  2156.                 new = inboth(lmp->in, rmp->in);
  2157.                 if (new == NULL)
  2158.                     goto done;
  2159.                 freelist(lmp->in);
  2160.                 free((char *) lmp->in);
  2161.                 lmp->in = new;
  2162.             }
  2163.             break;
  2164.         case _PLUS:
  2165.             if (mp <= musts)
  2166.                 goto done;    /* "cannot happen" */
  2167.             --mp;
  2168.             mp->is[0] = '\0';
  2169.             break;
  2170.         case _END:
  2171.             if (mp != &musts[1])
  2172.                 goto done;    /* "cannot happen" */
  2173.             for (i = 0; musts[0].in[i] != NULL; ++i)
  2174.                 if (strlen(musts[0].in[i]) > strlen(result))
  2175.                     result = musts[0].in[i];
  2176.             goto done;
  2177.         case _CAT:
  2178.             if (mp < &musts[2])
  2179.                 goto done;    /* "cannot happen" */
  2180.             {
  2181.                 register must *    lmp;
  2182.                 register must *    rmp;
  2183.  
  2184.                 rmp = --mp;
  2185.                 lmp = --mp;
  2186.                 /*
  2187.                 ** In.  Everything in left, plus everything in
  2188.                 ** right, plus catenation of
  2189.                 ** left's right and right's left.
  2190.                 */
  2191.                 lmp->in = addlists(lmp->in, rmp->in);
  2192.                 if (lmp->in == NULL)
  2193.                     goto done;
  2194.                 if (lmp->right[0] != '\0' &&
  2195.                     rmp->left[0] != '\0') {
  2196.                         register char *    tp;
  2197.  
  2198.                         tp = icpyalloc(lmp->right);
  2199.                         if (tp == NULL)
  2200.                             goto done;
  2201.                         tp = icatalloc(tp, rmp->left);
  2202.                         if (tp == NULL)
  2203.                             goto done;
  2204.                         lmp->in = enlist(lmp->in, tp,
  2205.                             strlen(tp));
  2206.                         free(tp);
  2207.                         if (lmp->in == NULL)
  2208.                             goto done;
  2209.                 }
  2210.                 /* Left-hand */
  2211.                 if (lmp->is[0] != '\0') {
  2212.                     lmp->left = icatalloc(lmp->left,
  2213.                         rmp->left);
  2214.                     if (lmp->left == NULL)
  2215.                         goto done;
  2216.                 }
  2217.                 /* Right-hand */
  2218.                 if (rmp->is[0] == '\0')
  2219.                     lmp->right[0] = '\0';
  2220.                 lmp->right = icatalloc(lmp->right, rmp->right);
  2221.                 if (lmp->right == NULL)
  2222.                     goto done;
  2223.                 /* Guaranteed to be */
  2224.                 if (lmp->is[0] != '\0' && rmp->is[0] != '\0') {
  2225.                     lmp->is = icatalloc(lmp->is, rmp->is);
  2226.                     if (lmp->is == NULL)
  2227.                         goto done;
  2228.                 }
  2229.             }
  2230.             break;
  2231.         default:
  2232.             if (t < _END) {
  2233.                 /* "cannot happen" */
  2234.                 goto done;
  2235.             } else if (t == '\0') {
  2236.                 /* not on *my* shift */
  2237.                 goto done;
  2238.             } else if (t >= _SET) {
  2239.                 /* easy enough */
  2240.                 resetmust(mp);
  2241.             } else {
  2242.                 /* plain character */
  2243.                 resetmust(mp);
  2244.                 mp->is[0] = mp->left[0] = mp->right[0] = t;
  2245.                 mp->is[1] = mp->left[1] = mp->right[1] = '\0';
  2246.                 mp->in = enlist(mp->in, mp->is, 1);
  2247.                 if (mp->in == NULL)
  2248.                     goto done;
  2249.             }
  2250.             break;
  2251.         }
  2252.         ++mp;
  2253.     }
  2254. done:
  2255.     (void) strncpy(reg->must, result, MUST_MAX - 1);
  2256.     reg->must[MUST_MAX - 1] = '\0';
  2257.     reg->mustn = strlen(reg->must);
  2258.     mp = musts;
  2259.     for (i = 0; i <= reg->tindex; ++i) {
  2260.         freelist(mp[i].in);
  2261.         ifree((char *) mp[i].in);
  2262.         ifree(mp[i].left);
  2263.         ifree(mp[i].right);
  2264.         ifree(mp[i].is);
  2265.     }
  2266.     free((char *) mp);
  2267. }
  2268.